const { exec } = require('../db/mysql')

const getList = (author, keyword) => {
    let sql = 'select * from blogs where 1=1 '
    if (author) {
        sql += `and author ='${author}' `
    }
    if (keyword) {
        sql += `and title like  '%${keyword}%' `
    }

    sql += 'order by createtime desc;'
    //返回数据
    return exec(sql)
}
const getDetail = (id) => {
    let sql = `select * from blogs where id='${id}';`
    //返回数据
    return exec(sql)
}

const newBlog = (blogData) => {
    //blogData是一个博客对象，包含title，id，content，createTime,author
    let [title, content, createtime, author] = [blogData.title, blogData.content, Date.now(), blogData.author]
    // console.log(title);
    let sql = `
    insert into blogs (title,content,createtime,author) 
    values('${title}', '${content}', '${createtime}', '${author}');
    `
    //返回数据
    return exec(sql).then(insertData => {
        return { id: insertData.insertId }
    })
}
const updataBlog = (id, blogData) => {
    //blogData是一个博客对象，包含title，id，content，createTime,author
    console.log('blogData....id', blogData, id);
    let [title, content, createtime] = [blogData.title, blogData.content, Date.now()]
    let sql = `
    update blogs set title = '${title}',content='${content}' 
    , createtime='${createtime}'  where id = '${id};'
    `
    return exec(sql).then(updataData => {
        if (updataData.affectedRows > 0) {
            return true
        }
        return false
    })
}
const deleteBlog = (id, author) => {
    //blogData是一个博客对象，包含title，id，content，createTime,author
    // console.log('id', id);
    // console.log('aaaa');
    let sql = `delete from blogs  where id = '${id}' and author = '${author}';`
    return exec(sql).then(delData => {
        if (delData.affectedRows > 0) {
            return true
        }
        return false
    })
}
module.exports = {
    getList,
    getDetail,
    newBlog,
    updataBlog,
    deleteBlog
}